package lockmanager;

import java.util.LinkedList;
import java.util.List;

public class ResourcePoolBlocking implements ResourcePool{
	
	private Object lock = new Object();
	private int poolSize = 10;
	private int contentionSize = 0;
	private int capacity = 10;
	private int position = 0;
	
	
	private List<Object> resourceList;
	
	public ResourcePoolBlocking(){
		resourceList = new LinkedList<Object>();
		for(int i=0;i<poolSize;i++){
			resourceList.add(i,i+1);
		}
	}

	@Override
	public int getPoolSize() {
		return this.poolSize;
	}

	@Override
	public int getContentionSize() {
		return this.contentionSize;
	}

	@Override
	public int getCapacity() {
		return this.capacity;
	}

	@Override
	public void setResurceList(List<? extends Object> resource) {
		this.resourceList = (List<Object>) resource;
	}

	@Override
	public List<? extends Object> getResouceList() {
		return this.resourceList;
	}

	@Override
	public Object get() {
		
		Object element = null;
		
		synchronized(lock){
			while(position >= poolSize){
				try {
					//System.out.println("I am waiting..");
					lock.wait();
					//System.out.println("I am awaking...");
				} catch (InterruptedException e) {
					return null;
				}
			}
			element = resourceList.set(position,null);
			position++;
		}
		return element;
	}

	@Override
	public boolean put(Object element) {
		
		synchronized(lock){
			if(position <= 0)
				return false;
			position--;
			resourceList.set(position, element);
			lock.notifyAll();
		}
		return true;
	}

}
